package com.project.server.service.impl;

import com.project.server.dto.LoginRequest;
import com.project.server.dto.LoginResponse;
import com.project.server.exception.BusinessException;
import com.project.server.mapper.AuthMapper;
import com.project.server.model.AdminUser;
import com.project.server.service.AuthService;
import com.project.server.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthMapper authMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public LoginResponse login(LoginRequest request) {
        log.info("开始处理登录请求: {}", request.getUsername());
        try {
            // 根据用户名查询用户
            AdminUser adminUser = authMapper.findByUsername(request.getUsername());
            log.debug("查询到的用户信息: {}", adminUser);
            
            if (adminUser == null) {
                log.warn("用户名不存在: {}", request.getUsername());
                throw new BusinessException("用户名或密码错误");
            }

            // 校验密码
            if (!passwordEncoder.matches(request.getPassword(), adminUser.getPassword())) {
                log.warn("密码错误: {}", request.getUsername());
                throw new BusinessException("用户名或密码错误");
            }

            // 生成token
            String token = jwtUtil.generateToken(adminUser.getId(), adminUser.getUsername());
            log.info("登录成功，生成token: {}", token);

            // 返回登录响应
            return LoginResponse.builder()
                    .token(token)
                    .userInfo(adminUser)
                    .build();
        } catch (Exception e) {
            log.error("登录失败", e);
            throw e;
        }
    }
}
